package org.ucas.faker.web.fetcher.parse;

import javafx.util.Pair;
import jdk.nashorn.internal.scripts.JO;
import org.ucas.faker.web.fetcher.cond.FetchCond;
import org.ucas.faker.web.fetcher.meta.ColumnField;
import org.ucas.faker.web.fetcher.meta.Table;
import org.ucas.faker.web.fetcher.op.Join;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JoinGraph implements Serializable {

  public static class JoinEdge implements Serializable {
    public Table target;

    public Join join;

    public JoinEdge(Table target, Join join) {
      this.target = target;
      this.join = join;
    }
  }

  Map<Table,List<JoinEdge>> data = new HashMap<>();

  private void addEdge(Table left, Table right, FetchCond cond) {
    if(!data.containsKey(left)) data.put(left,new ArrayList<>());
    List<JoinEdge> conns = data.get(left);

    Join join = new Join();
    join.right = left;
    join.left = right;
    join.cond = cond;

    conns.add(new JoinEdge(right,join));
  }

  public void connect(Table left, Table right,FetchCond cond) {
    addEdge(left,right,cond);
    addEdge(right,left,cond);
  }

  public List<JoinEdge> edges(Table table) {
    return data.getOrDefault(table,new ArrayList<>());
  }

  public JoinEdge edge(Table left, Table right) {
    List<JoinEdge> cands = edges(left);
    for(JoinEdge cand:cands)
      if(cand.target.equals(right)) return cand;
    return null;
  }
}
